package cn.springcloud.fix.saas.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;

/**
 * ResourceServerConfig 优先级高于 WebSecurityConfig
 */
@Slf4j
@Configuration
@EnableResourceServer  // 开启 OAuth2AuthenticationProcessingFilter 过滤器
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // .antMatchers("/user").permitAll()
                .anyRequest().authenticated();

        // http
        //         .requestMatcher(new OAuthRequestedMatcher())
        //         .authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll()
    }

    private static class OAuthRequestedMatcher implements RequestMatcher {
        public boolean matches(HttpServletRequest request) {
            String auth = request.getHeader("Authorization");
            // Determine if the client request contained an OAuth Authorization
            boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer");
            boolean haveAccessToken = request.getParameter("access_token") != null;
            return haveOauth2Token || haveAccessToken;
        }
    }

    /*@Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId("saas-api").stateless(true)
                .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
        ;
    }*/
}
